package models;

import java.util.*;
import javax.persistence.*;

import play.Logger;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * User entity managed by Ebean
 */
@Entity
@Table(name="OnHold")
public class OnHold extends Model {

	@Id
	public Long id;

	public String seat_no;
	public Date created_time;

	@ManyToOne
	public MovieSession session;

    // -- Queries
    public static Model.Finder<Long,OnHold> find = new Model.Finder(Long.class, OnHold.class);

	public OnHold(Long session, String seat) {
		this.seat_no = seat;
		this.session = MovieSession.find.byId(session);
		this.created_time = new Date();
	}


    public static List<OnHold> findBySession(Long session) {
    	Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, -5);
		Date deadline = cal.getTime();
		List<OnHold> records = find.fetch("session").where().eq("session_id",session).lt("created_time", deadline).findList();

		for(OnHold record : records){
			record.delete();
		}

		return find.fetch("session").where().eq("session_id",session).findList();
    }

    public static boolean startHolding(Long session, String[] seats){
    	for(int i=0;i<seats.length;i++){
	    	new OnHold(session,seats[i]).save();
    	}
    	return true;
    }

    public static boolean endHolding(Long session, String[] seats) {
		List<OnHold> records = find.fetch("session").where().eq("session_id", session).findList();
		for(OnHold record : records){
			if(Arrays.asList(seats).contains(record.seat_no)){
				record.delete();
			}
		}

		return true;
    }

}

